package com.zzh.ytapigateway;

import com.zzh.demo.utils.SignUtils;
import com.zzh.ytapi.ytapicommon.model.entity.InterfaceInfo;
import com.zzh.ytapi.ytapicommon.model.entity.User;
import com.zzh.ytapi.ytapicommon.service.InnerInterfaceInfoService;
import com.zzh.ytapi.ytapicommon.service.InnerUserInterfaceInfoService;
import com.zzh.ytapi.ytapicommon.service.InnerUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
@Component
public class CustomGlobalFilter implements GlobalFilter, Ordered {

    public static final String Host= "http://localhost:8123";

    @DubboReference
    private InnerInterfaceInfoService innerInterfaceInfoService;

    @DubboReference
    private InnerUserService innerUserService;

    @DubboReference
    private InnerUserInterfaceInfoService innerUserInterfaceInfoService;

    public static final List<String> IP_WHITE_LIST = Arrays.asList("127.0.0.1","124.222.212.80");

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
//        1.用户发送请求到API网关
//        2.请求日志

        ServerHttpRequest request = exchange.getRequest();
        String path = Host+request.getPath().value();
        String method = request.getMethod().toString();
        log.info("请求唯一标识"+request.getId());
        log.info("请求路径"+path);
        log.info("请求方法"+method);
        log.info("请求参数"+request.getQueryParams());
        log.info("请求来源地址"+request.getRemoteAddress());
        String hostString = request.getLocalAddress().getHostString();
        log.info("请求来源地址"+hostString);
        ServerHttpResponse response = exchange.getResponse();
//        3.(黑白名单)
        if (!IP_WHITE_LIST.contains(hostString)){
            return handleNoAuth(response);
        }
//        4.用户鉴权（判断ak、sk是否合法）
        HttpHeaders headers = request.getHeaders();
        String accessKey= headers.getFirst("accessKey");
        String nonce= headers.getFirst("nonce");
        String timestamp= headers.getFirst("timestamp");
        String sign= headers.getFirst("sign");
        String body= headers.getFirst("body");
//        todo    实际应该要到数据库中查 这个用户是否有访问的权限以及secretKey
        User user = null;
        try {
            user = innerUserService.getInvokerUser(accessKey);
        }catch (Exception e){
            log.error("getuser error",e);
        }

        if (user == null){
            return handleNoAuth(response);
        }
//        if (!accessKey.equals("aaa")){
//            return handleNoAuth(response);
//        }
        if (Long.parseLong(nonce)>10000L){
            return handleNoAuth(response);
        }
//        时间和当前时间不能超过15分钟
        long currentTime = System.currentTimeMillis() / 1000;
        long FIVE_MINEUTES = 60 * 5L;
        if ((currentTime - Long.parseLong(timestamp)) >= FIVE_MINEUTES){
           return handleNoAuth(response);
        }
//        todo 随机数可以存到redis  时间戳校验 不能和当前时间差五分钟
//        todo 实际情况从数据库查出secretKey
        String serverSign = SignUtils.getSign(body, user.getSecretKey());

        if (sign==null || !sign.equals(serverSign)){
           return handleNoAuth(response);
        }

//        todo 5.请求的模拟接口是否存在？
        InterfaceInfo interfaceInfo = null;

        try {
            interfaceInfo = innerInterfaceInfoService.getInterfaceInfo(path, method);
        }catch (Exception e){
            log.error("getInterfaceinfo error",e);
        }

        if (interfaceInfo == null){
            return handleNoAuth(response);
        }
//        6。请求转发，调用模拟接口
//        Mono<Void> filter = chain.filter(exchange);
//        7.响应日志
        return handleResponse(exchange, chain,interfaceInfo.getId(),user.getId());
////        8.调用成功，接口调用次数+1
//        if(response.getStatusCode()== HttpStatus.OK){
//
//        }else {
////        9.调用失败，返回一个规范的错误码
//            return handleInvokeError(response);
//        }
//
//        log.info("custom global filter");
//        return chain.filter(exchange);
    }

    /**
     * 处理响应
     * @param exchange
     * @param chain
     * @return
     */
    public Mono<Void> handleResponse(ServerWebExchange exchange, GatewayFilterChain chain,long interfaceInfoId, long userId) {
        try {
            //从交换机拿到响应对象
            ServerHttpResponse originalResponse = exchange.getResponse();
            //缓冲区工厂，拿到缓存数据
            DataBufferFactory bufferFactory = originalResponse.bufferFactory();
            //拿到响应码
            HttpStatus statusCode = originalResponse.getStatusCode();

            if(statusCode == HttpStatus.OK){
                //装饰器，增强能力
                ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(originalResponse) {
                //等调用完转发的接口才会执行
                    @Override
                    public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                        log.info("body instanceof Flux: {}", (body instanceof Flux));
                         //如果对象是响应式的
                        if (body instanceof Flux) {
                            //拿到真正的body
                            Flux<? extends DataBuffer> fluxBody = Flux.from(body);
                            //往返回值写数据 拼接字符串
                            return super.writeWith(fluxBody.map(dataBuffer -> {
                                // todo 8.调用成功，接口调用次数+1  try catch 快捷键ctrl+alt+T
                                try {
                                    innerUserInterfaceInfoService.invokeCount(interfaceInfoId, userId);
                                } catch (Exception e){
                                    log.error("invokeCount error",e);

                                }

                                byte[] content = new byte[dataBuffer.readableByteCount()];
                                dataBuffer.read(content);
                                DataBufferUtils.release(dataBuffer);//释放掉内存
                                // 构建日志
                                StringBuilder sb2 = new StringBuilder(200);
                                sb2.append("<--- {} {} \n");
                                List<Object> rspArgs = new ArrayList<>();
                                rspArgs.add(originalResponse.getStatusCode());
                                //rspArgs.add(requestUrl);
                                String data = new String(content, StandardCharsets.UTF_8);//data
                                sb2.append(data);
                                //打印日志
                                log.info("响应结果: "+ data);
                                return bufferFactory.wrap(content);
                            }));
                        } else {
                            //9.调用失败，返回一个规范的错误码
                            log.error("<--- {} 响应code异常", getStatusCode());
                        }
                        return super.writeWith(body);
                    }
                };
                 //设置response对象是我们刚刚装饰过的
                return chain.filter(exchange.mutate().response(decoratedResponse).build());
            }
            return chain.filter(exchange);//降级处理返回数据
        }catch (Exception e){
            log.error("网关处理响应异常" + e);
            return chain.filter(exchange);
        }


    }

    private Mono<Void> handleNoAuth(ServerHttpResponse response) {
//        403
        response.setStatusCode(HttpStatus.FORBIDDEN);
        return response.setComplete();
    }
    private Mono<Void> handleInvokeError(ServerHttpResponse response) {
//        500
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }
}